package com.ldw.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ldw.mapper.ArticleBodyMapper;
import com.ldw.mapper.ArticleMapper;
import com.ldw.mapper.ArticleTagMapper;
import com.ldw.mapper.CategoryMapper;
import com.ldw.mapper.dos.Archives;
import com.ldw.pojo.*;
import com.ldw.service.ArticleService;
import com.ldw.service.SysUserService;
import com.ldw.service.TagService;
import com.ldw.service.ThreadService;
import com.ldw.utils.UserThreadLocal;
import com.ldw.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ThreadService threadService;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    // 分页查询
    @Override
    public Result listArticle(PageParams params) {
        Page<Article> page = new Page<>(params.getPage(), params.getPageSize());
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        if (params.getCategoryId() != null) {
            wrapper.eq(Article::getCategoryId, params.getCategoryId());
        }
        List<Long> articleIdList = new ArrayList<>();
        if (params.getTagId() != null) {
            LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(ArticleTag::getArticleId, params.getTagId());
            List<ArticleTag> articleTags = articleTagMapper.selectList(queryWrapper);
            for (ArticleTag articleTag : articleTags) {
                articleIdList.add(articleTag.getArticleId());
            }
            wrapper.in(Article::getId, articleIdList);
        }
        //是否置顶排序
        wrapper.orderByDesc(Article::getWeight);
        //按照创建时间降序
        wrapper.orderByDesc(Article::getCreateDate);
        Page<Article> articlePage = articleMapper.selectPage(page, wrapper);
        List<Article> records = articlePage.getRecords();
        List<ArticleVo> articleVoList = copyList(records, true, true, false, false);
        return Result.success(articleVoList);
    }

    @Override
    public Result hotArticle(int limit) {
        //mybatis写法
      /*  List<Article> articleList = articleMapper.hotArticle(limit);
        return Result.success(articleList);*/
        //mybatisPlus写法
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId, Article::getTitle, Article::getCreateDate);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false, false, false));
    }

    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getCreateDate, Article::getTitle);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false, false, false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Override
    public Result articleView(long articleId) {
        /*
         * 1.根据id查询， 文章信息
         * 2.根据bodyId和categoryId 去做关联
         * */
        Article article = articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article, true, true, true, true);
        threadService.updateArticlerViewCount(articleMapper, article);
        return Result.success(articleVo);
    }

    //文章发布
    @Override
    public Result publish(ArticleParam articleParam) {
        /*
        1.构建Article对象
        2.作者id 当前的登录用户
        3.标签要将标签加入到关联表中
        4.body内容存储
        * */
        SysUser sysUser = UserThreadLocal.get();
        Article article = new Article();
        article.setAuthorId(1l);
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(articleParam.getCategory().getId());
        articleMapper.insert(article);
        //tag
        List<TageVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TageVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(tag.getId());
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //tag
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", article.getId().toString());
        return Result.success(map);
    }

    private List<ArticleVo> copyList(List<Article> records, Boolean isTag, Boolean isAuthor, Boolean isBody, Boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor, isBody, isCategory));
        }
        return articleVoList;
    }

    private ArticleVo copy(Article article, Boolean isTag, Boolean isAuthor, Boolean isBody, Boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        articleVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(article.getCreateDate()));
        if (isTag) {
            List<TageVo> tageVoList = tagService.queryByArticleId(article.getId());
            articleVo.setTags(tageVoList);
        }
        if (isAuthor) {
            SysUser sysUser = sysUserService.queryAuthorById(article.getAuthorId());
            articleVo.setAuthor(sysUser.getNickname());
        }
        if (isBody) {
            ArticleBodyVo articleBodyVo = new ArticleBodyVo();
            ArticleBody articleBody = articleBodyMapper.selectById(article.getBodyId());
            articleBodyVo.setContent(articleBody.getContent());
            articleVo.setBody(articleBodyVo);
        }
        if (isCategory) {
            CategoryVo categoryVo = new CategoryVo();
            Category category = categoryMapper.selectById(article.getCategoryId());
            categoryVo.setId(category.getId());
            categoryVo.setAvater(category.getAvatar());
            categoryVo.setCategoryName(category.getCategoryName());
            articleVo.setCategory(categoryVo);
        }
        return articleVo;
    }
}
